<?php

/**
 * 语言包核心类
 *
 * @author jonwang(jonwang@myqee.com)
 * @category   MyQEE
 * @package    System
 * @subpackage Core
 * @copyright  Copyright (c) 2008-2011 myqee.com
 * @license    http://www.myqee.com/license.html
 */
class MyQEE_Core_I18n
{

    /**
     * 默认语言
     * @var string
     */
    protected $lang = 'cn';

    protected static $data = array();

    public function __construct($lang = null)
    {
        if ( null === $lang )
        {
            static $default_lang = null;
            if ( null === $default_lang )
            {
                $default_lang = Core::config('core.lang');
                if ( ! $default_lang )
                {
                    $default_lang = 'zh_CN';
                }
            }
            $lang = $default_lang;
        }
        $this->lang = $lang;
    }

    /**
     *
     * @return I18n_En
     */
    public function get($string)
    {
        if ( ! isset(Core_I18n::$data[$this->lang]) )
        {
            Core_I18n::load($this->lang);
        }
        if ( isset(Core_I18n::$data[$this->lang][$string]) )
        {
            return Core_I18n::$data[$this->lang][$string];
        }
        return $string;
    }

    /**
     * 加载语言包文件
     * @link http://www.php.net/manual/en/function.parse-ini-file.php
     */
    public function load()
    {
        $langdata = array();
        $files = Core::find_file('i18n', $this->lang, '.lang');
        if ( $files )
        {
            $ext_len = strlen(EXT);
            if ( count($files) > 1 )
            {
                krsort($files); //逆向排序
            }
            foreach ( $files as $langfile )
            {
                if ( substr($langfile, - $ext_len) === EXT )
                {
                    $lang = Core_I18n::_include_lang_file($langfile);
                }
                else
                {
                    $lang = @parse_ini_file($langfile);
                }
                
                if ( is_array($lang) )
                {
                    $langdata = array_merge($langdata, $lang);
                }
            }
        }
        Core_I18n::$data[$this->lang] = $langdata;
    }

    protected static function _include_lang_file($file)
    {
        $lang = array();
        include $file;
        return $lang;
    }
}